import song, { SONG_TYPE } from 'apis/song'
import useAsyncFn from 'hooks/useAsyncFn'
import React, { memo, useCallback, useContext, useEffect, useState } from 'react'
import { ACTIONS, PlayMusicContext } from 'reducers/playMusic'
import styles from './style.module.css'
import cn from 'classnames'
import { TABS } from 'constants/LatestMusic'
import { Spinner } from '@blueprintjs/core'
import Content from './Content'
import { createMusic } from 'helpers/business'
const LatestMusic = memo(() => {
  const [_, playDispatch] = useContext(PlayMusicContext)
  const [state, getTopSongsFn] = useAsyncFn(song.getTopSongs)
  const { value: res, loading } = state
  const [selectType, setSelectType] = useState(SONG_TYPE.ALL)
  useEffect(() => {
    getTopSongsFn(selectType)
  }, [])

  const handleTypeChange = useCallback((type) => {
    setSelectType(type)
    getTopSongsFn(type)
  }, [])
  const playAll = useCallback(
    (autoPlay?: boolean) => {
      playDispatch({
        type: ACTIONS.SET_PLAY_LIST,
        payload: {
          playList: res,
        },
      })
      if (autoPlay) {
        const item = res![0]

        playDispatch({
          type: ACTIONS.PLAY,
          payload: {
            musicId: item?.id,
            music: createMusic({
              ...item!,
              duration: item.duration / 1000,
              picUrl: item?.picUrl || item?.album?.blurPicUrl,
            }),
          },
        })
      }
    },
    [res],
  )
  return (
    <div className={styles.root}>
      <div className={styles.header}>
        <div className={styles.tabs}>
          {TABS.map((v) => {
            const { type, label } = v
            return (
              <div
                key={type}
                className={cn(styles.tab, selectType === type && styles.active)}
                onClick={() => handleTypeChange(type)}
              >
                {label}
              </div>
            )
          })}
        </div>
        <div className={styles.operations}>
          <div className={styles.playAll} onClick={() => playAll(true)}>
            播放全部
          </div>
        </div>
      </div>
      <div className={styles.content}>{loading ? <Spinner /> : <Content data={res} />}</div>
    </div>
  )
})
export default LatestMusic
